import React, { useState, useEffect, useRef } from 'react';
import { Button, Space, Modal, message, Table, Badge, DatePicker, Radio } from 'antd';
import dayjs from 'dayjs';
import request from '@/utils/request';
import DataReleaseModal from '@/components/DataReleaseModal';
import { useNavigate } from 'react-router-dom';
import DraggableTable from '@/components/DraggableTable';
import ReleaseListModal from './ReleaseListModal';

const DataTableActions = ({
  advanced,
  selectedRowKeys,
  setSelectedRowKeys,
  dataKey,
  tableData,
  filterParams,
  dataLevel,
  fetchTableData,
  fetchDataLevel,
  fetchFilterOptions,
  type,
  columns: propColumns,
  refreshDownloadingCount
}) => {
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [downloadAllLoading, setDownloadAllLoading] = useState(false);
  const [releaseModalOpen, setReleaseModalOpen] = useState(false);
  const [releaseType, setReleaseType] = useState(1);
  const [sciencePendingReleaseList, setSciencePendingReleaseList] = useState([]);
  const [otherPendingReleaseList, setOtherPendingReleaseList] = useState([]);
  const [listReleaseModalOpen, setListReleaseModalOpen] = useState(false);
  const [releaseAllLoading, setReleaseAllLoading] = useState(false);
  const [favoriteAllLoading, setFavoriteAllLoading] = useState(false);
  const [scheduledReleaseAllLoading, setScheduledReleaseAllLoading] = useState(false);
  const [cancelReleaseAllLoading, setCancelReleaseAllLoading] = useState(false);
  const [scheduledReleaseAllModalOpen, setScheduledReleaseAllModalOpen] = useState(false);
  const [scheduledTime, setScheduledTime] = useState<string>(dayjs().format('YYYY-MM-DD HH:mm:ss'));
  const [operationMode, setOperationMode] = useState<'selected' | 'all'>('selected');
  const navigate = useNavigate();

  // 判断当前类型
  const isScience = type === 'science';
  const pendingReleaseList = isScience ? sciencePendingReleaseList : otherPendingReleaseList;
  const setPendingReleaseList = isScience ? setSciencePendingReleaseList : setOtherPendingReleaseList;

  // 选中数据转为接口格式
  const getSelectedFiles = () =>
    selectedRowKeys
      .map((key) => {
        const item = tableData.find((d) => d.key === key);
        return item ? { data_type: item.data_type, product_id: item.key } : null;
      })
      .filter((item) => item !== null);

  // 批量下载
  const handleBatchDownload = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要下载的数据');
      return;
    }
    setDownloadLoading(true);
    try {
      const payload = {
        query_params: {
          data_key: dataKey,
          ...filterParams
        },
        is_favorites: false,
        files: selectedRowKeys.map((key) => ({
          data_type: tableData.find((item) => item.key === key)?.data_type,
          product_id: key
        }))
      };
      const response = await request.post('/Management/DownloadOrder', payload);
      if (response.status === 200) {
        message.success('请到“下载订单”中查看拟下载数据的准备情况', 5);
        setSelectedRowKeys([]);
        try { refreshDownloadingCount && refreshDownloadingCount(); } catch(e) {}
      }
    } catch (error) {
      message.error(error?.message || '创建下载订单失败');
    } finally {
      setDownloadLoading(false);
    }
  };

  // 全部下载
  const handleDownloadAll = async () => {
    setDownloadAllLoading(true);
    try {
      const response = await request.get(advanced ? '/Management/AdvancedDataDownloadAll' : '/Management/DownloadOrderListAll', {
        params: {
          data_key: dataKey,
          ...filterParams,
          data_level: dataLevel
        }
      });
      if (response.status === 200) {
        message.success('请到“下载订单”中查看拟下载数据的准备情况', 5);
        try { refreshDownloadingCount && refreshDownloadingCount(); } catch(e) {}
      }
    } catch (error) {
      message.error(error?.message || '创建下载订单失败');
    } finally {
      setDownloadAllLoading(false);
    }
  };

  // 批量收藏
  const handleBatchFavorite = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要收藏的数据');
      return;
    }
    try {
      const payload = {
        files: selectedRowKeys.map((key) => ({
          data_type: tableData.find((item) => item.key === key)?.data_type,
          product_id: key
        }))
      };
      const response = await request.post('/Management/Favorites', payload);
      if (response.status === 200) {
        message.success('批量收藏成功');
        setSelectedRowKeys([]);
        fetchTableData && fetchTableData();
      }
    } catch (error) {
      message.error(error?.message || '收藏失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的数据');
      return;
    }
    Modal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: selectedRowKeys.map((key) => ({
              data_type: tableData.find((item) => item.key === key)?.data_type,
              product_id: key
            }))
          };
          const response = await request.post('/Management/DataDelete', payload);
          if (response.status === 200) {
            message.success('批量删除成功');
            setSelectedRowKeys([]);
            fetchTableData && fetchTableData();
            fetchDataLevel && fetchDataLevel();
            fetchFilterOptions && fetchFilterOptions();
          }
        } catch (error) {
          message.error(error?.message || '删除失败');
        }
      }
    });
  };

  // 批量取消发布
  const handleBatchCancelRelease = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要取消发布的数据');
      return;
    }
    Modal.confirm({
      title: '确认批量取消发布',
      content: `确定要取消发布选中的 ${selectedRowKeys.length} 条数据吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const payload = {
            files: selectedRowKeys.map((key) => ({
              data_type: tableData.find((item) => item.key === key)?.data_type,
              product_id: key
            }))
          };
          const response = await request.post('/Management/DataCancelRelease', payload);
          if (response.status === 200) {
            message.success('批量取消发布成功');
            setSelectedRowKeys([]);
            fetchTableData && fetchTableData();
          }
        } catch (error) {
          message.error(error?.message || '取消发布失败');
        }
      }
    });
  };

  // 发布弹窗
  const handleRelease = (type) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要发布的数据');
      return;
    }
    setReleaseType(type);
    setReleaseModalOpen(true);
  };

  // 添加至发布列表（本地）
  const handleAddToReleaseList = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要添加的数据');
      return;
    }
    // 选中的完整数据
    const selectedFiles = selectedRowKeys
      .map((key) => {
        const item = tableData.find((d) => d.key === key);
        return item || null;
      })
      .filter((item) => item !== null);
    // 去重：只添加未在pendingReleaseList中的数据
    const newFiles = selectedFiles.filter(
      (file) => !pendingReleaseList.some(
        (item) => (item.product_id || item.key) === (file.product_id || file.key) && item.data_type === file.data_type
      )
    );
    console.log('newFiles', newFiles, selectedFiles, pendingReleaseList);
    if (newFiles.length === 0) {
      message.info('选中的数据已全部在发布列表中');
      return;
    }
    setPendingReleaseList([...pendingReleaseList, ...newFiles]);
    setSelectedRowKeys([]);
    message.success('已添加至发布列表');
  };

  // 全部发布
  const handleReleaseAll = async () => {
    setReleaseAllLoading(true);
    try {
      const response = await request.get('/Management/DataReleaseAll', {
        params: {
          data_key: dataKey,
          ...filterParams,
          data_level: dataLevel
        }
      });
      if (response.status === 200) {
        message.success(`全部发布成功！`);
        fetchTableData && fetchTableData();
      }
    } catch (error) {
      message.error(error?.message || '全部发布失败');
    } finally {
      setReleaseAllLoading(false);
    }
  };

  // 全部收藏
  const handleFavoriteAll = async () => {
    setFavoriteAllLoading(true);
    try {
      const response = await request.get('/Management/FavoritesAll', {
        params: {
          data_key: dataKey,
          ...filterParams,
          data_level: dataLevel
        }
      });
      if (response.status === 200) {
        message.success('全部收藏成功');
        fetchTableData && fetchTableData();
      }
    } catch (error) {
      message.error(error?.message || '全部收藏失败');
    } finally {
      setFavoriteAllLoading(false);
    }
  };

  // 全部定时发布
  const handleScheduledReleaseAll = () => {
    setScheduledReleaseAllModalOpen(true);
  };

  // 全部取消发布
  const handleCancelReleaseAll = async () => {
    Modal.confirm({
      title: '确认全部取消发布',
      content: '确定要取消发布当前筛选条件下的所有数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        setCancelReleaseAllLoading(true);
        try {
          const response = await request.get('/Management/DataCancelReleaseAll', {
            params: {
              data_key: dataKey,
              ...filterParams,
              data_level: dataLevel
            }
          });
          if (response.status === 200) {
            message.success('全部取消发布成功');
            fetchTableData && fetchTableData();
          }
        } catch (error) {
          message.error(error?.message || '全部取消发布失败');
        } finally {
          setCancelReleaseAllLoading(false);
        }
      }
    });
  };

  return (
    <>
      <Space>
        <Radio.Group 
          value={operationMode} 
          onChange={(e) => setOperationMode(e.target.value)}
          style={{ marginRight: 16, whiteSpace: 'nowrap' }}
        >
          <Radio value="selected">选中数据</Radio>
          <Radio value="all">全部数据</Radio>
        </Radio.Group>
        
        {operationMode === 'selected' ? (
          <>
            <Button type="primary" loading={downloadLoading} onClick={handleBatchDownload}>
              下载
            </Button>
            <Button type="primary" onClick={handleBatchFavorite}>
              收藏
            </Button>
            <Button type="primary" onClick={() => handleRelease(1)}>
              立即发布
            </Button>
            <Button type="primary" onClick={() => handleRelease(2)}>
              定时发布
            </Button>
            <Button danger onClick={handleBatchCancelRelease}>
              取消发布
            </Button>
            <Button danger onClick={handleBatchDelete}>
              删除
            </Button>
          </>
        ) : (
          <>
            <Button type="primary" loading={downloadAllLoading} onClick={handleDownloadAll}>
              下载
            </Button>
            <Button type="primary" loading={favoriteAllLoading} onClick={handleFavoriteAll}>
              收藏
            </Button>
            <Button type="primary" loading={releaseAllLoading} onClick={handleReleaseAll}>
              立即发布
            </Button>
            <Button type="primary" onClick={handleScheduledReleaseAll}>
              定时发布
            </Button>
            <Button danger loading={cancelReleaseAllLoading} onClick={handleCancelReleaseAll}>
              取消发布
            </Button>
          </>
        )}
        <div className="button-divider"></div>
        <Button type="primary" onClick={handleAddToReleaseList}>
          添加至发布列表
        </Button>
        <span style={{ position: 'relative', display: 'inline-block', marginRight: 0 }}>
          <Button type="primary" onClick={() => setListReleaseModalOpen(true)}>
            发布列表
          </Button>
          {(pendingReleaseList.length > 0) && (
            <span
              style={{
                position: 'absolute',
                right: 6,
                top: -8,
                transform: 'translateX(50%)',
                background: '#faad14',
                color: '#fff',
                borderRadius: '10px',
                padding: '0 6px',
                fontSize: 12,
                lineHeight: '20px',
                minWidth: 20,
                textAlign: 'center',
                boxShadow: '0 0 0 1px #fff',
                zIndex: 1
              }}
            >
              {pendingReleaseList.length}
            </span>
          )}
        </span>
      </Space>
      <DataReleaseModal
        open={releaseModalOpen}
        onCancel={() => {
          setReleaseModalOpen(false);
          setReleaseType(0);
        }}
        releaseType={releaseType}
        files={getSelectedFiles()}
        onSuccess={() => {
          setReleaseModalOpen(false);
          setReleaseType(0);
          setSelectedRowKeys([]);
          fetchTableData && fetchTableData();
        }}
      />
      <ReleaseListModal
        visible={listReleaseModalOpen}
        onClose={() => setListReleaseModalOpen(false)}
        pendingReleaseList={pendingReleaseList}
        setPendingReleaseList={setPendingReleaseList}
        tableData={tableData}
        columns={propColumns}
        fetchTableData={fetchTableData}
      />
      <Modal
        title="全部定时发布"
        open={scheduledReleaseAllModalOpen}
        onCancel={() => setScheduledReleaseAllModalOpen(false)}
        onOk={async () => {
          setScheduledReleaseAllLoading(true);
          try {
            const response = await request.get('/Management/DataReleaseScheduledAll', {
              params: {
                data_key: dataKey,
                scheduled_release_time: scheduledTime,
                ...filterParams,
                data_level: dataLevel
              }
            });
            if (response.status === 200) {
              message.success(`全部定时发布成功！`);
              setScheduledReleaseAllModalOpen(false);
              fetchTableData && fetchTableData();
            }
          } catch (error) {
            message.error(error?.message || '全部定时发布失败');
          } finally {
            setScheduledReleaseAllLoading(false);
          }
        }}
        confirmLoading={scheduledReleaseAllLoading}
        okText="确认发布"
        cancelText="取消"
      >
        <div style={{ marginBottom: 16 }}>
          <label>发布时间：</label>
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm:ss"
            value={dayjs(scheduledTime)}
            onChange={(date) => setScheduledTime(date ? date.format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'))}
            style={{ width: '100%', marginTop: 8 }}
          />
        </div>
      </Modal>
    </>
  );
};

export default DataTableActions; 